package com.cmict.data.system.controller.admin.dict;

import com.cmict.data.framework.common.pojo.CommonResult;
import com.cmict.data.framework.common.pojo.PageResult;
import com.cmict.data.framework.excel.core.util.ExcelUtils;
import com.cmict.data.framework.operatelog.core.annotations.OperateLog;
import com.cmict.data.system.controller.admin.dict.vo.data.*;
import com.cmict.data.system.controller.admin.dict.vo.data.*;
import com.cmict.data.system.convert.dict.DictDataConvert;
import com.cmict.data.system.dal.dataobject.dict.DictDataDO;
import com.cmict.data.system.dal.mysql.dict.DictDataMapper;
import com.cmict.data.system.service.dict.DictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

import static com.cmict.data.framework.common.pojo.CommonResult.success;
import static com.cmict.data.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 字典数据")
@RestController
@RequestMapping("/system/dict-data")
@Validated
public class DictDataController {

    @Resource
    private DictDataService dictDataService;

    @Resource
    private DictDataMapper dictDataMapper;

    @PostMapping("/create")
    @ApiOperation("新增字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:create')")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Long> createDictData(@Valid @RequestBody DictDataCreateReqVO reqVO) {
        List<DictDataDO> list = dictDataService.getListByDictType(reqVO.getDictType());
        int sort = 1;
        for (DictDataDO dictDataDO:list) {
            if(sort!=reqVO.getSort()){
                dictDataDO.setSort(sort);
                // 更新到数据库
                dictDataMapper.updateById(dictDataDO);
                sort++;
            }else{
                sort++;
                dictDataDO.setSort(sort);
                // 更新到数据库
                dictDataMapper.updateById(dictDataDO);
                sort++;
            }
        }
        Long dictDataId = dictDataService.createDictData(reqVO);
        return success(dictDataId);
    }

    @PutMapping("update")
    @ApiOperation("修改字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:update')")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Boolean> updateDictData(@Valid @RequestBody DictDataUpdateReqVO reqVO) {
        List<DictDataDO> list = dictDataService.getListByDictType(reqVO.getDictType());
        int sort = 1;
        for (DictDataDO dictDataDO:list) {
            if(!dictDataDO.getId().equals(reqVO.getId())) {
                if (sort != reqVO.getSort()) {
                    dictDataDO.setSort(sort);
                    // 更新到数据库
                    dictDataMapper.updateById(dictDataDO);
                    sort++;
                } else {
                    sort++;
                    dictDataDO.setSort(sort);
                    // 更新到数据库
                    dictDataMapper.updateById(dictDataDO);
                    sort++;
                }
            }
        }
        dictDataService.updateDictData(reqVO);
        return success(true);
    }


    @DeleteMapping("/delete")
    @ApiOperation("删除字典数据")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:dict:delete')")
    public CommonResult<Boolean> deleteDictData(Long id) {
        dictDataService.deleteDictData(id);
        return success(true);
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获得全部字典数据列表", notes = "一般用于管理后台缓存字典数据在本地")
    // 无需添加权限认证，因为前端全局都需要
    public CommonResult<List<DictDataSimpleRespVO>> getSimpleDictDatas() {
        List<DictDataDO> list = dictDataService.getDictDatas();
        return success(DictDataConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("/获得字典类型的分页列表")
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    public CommonResult<PageResult<DictDataRespVO>> getDictTypePage(@Valid DictDataPageReqVO reqVO) {
        return success(DictDataConvert.INSTANCE.convertPage(dictDataService.getDictDataPage(reqVO)));
    }

    @GetMapping("/getListByDictType")
    @ApiOperation("/根据类型获得字典类型的列表")
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    @ApiImplicitParam(name = "dictType", value = "字典类型", required = true, example = "1024", dataTypeClass = String.class)
    public CommonResult<List<DictDataDO>> getListByDictType(@RequestParam("dictType") String dictType) {
        return success(dictDataService.getListByDictType(dictType));
    }

    /**
     * 和登录 接口类似
     * @param dictType
     * @return
     */
    @GetMapping("/getListByDictTypeNoAuth")
    @ApiOperation("/根据类型获得字典类型的列表")
    @ApiImplicitParam(name = "dictType", value = "字典类型", required = true, example = "1024", dataTypeClass = String.class)
    public CommonResult<List<DictDataDO>> getListByDictTypeNoAuth(@RequestParam("dictType") String dictType) {
        return success(dictDataService.getListByDictType(dictType));
    }
    @GetMapping("/getMessageListByDictType")
    @ApiOperation("/根据类型获得消息的列表")
//    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    @ApiImplicitParam(name = "dictType", value = "字典类型", required = true, example = "1024", dataTypeClass = String.class)
    public CommonResult<List<DictDataDO>> getMessageListByDictType(@RequestParam("dictType") String dictType) {
        return success(dictDataService.getMessageListByDictType(dictType));
    }

    @GetMapping(value = "/get")
    @ApiOperation("/查询字典数据详细")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    public CommonResult<DictDataRespVO> getDictData(@RequestParam("id") Long id) {
        return success(DictDataConvert.INSTANCE.convert(dictDataService.getDictData(id)));
    }

    @GetMapping("/export")
    @ApiOperation("导出字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:export')")
    @OperateLog(type = EXPORT)
    public void export(HttpServletResponse response, @Valid DictDataExportReqVO reqVO) throws IOException {
        List<DictDataDO> list = dictDataService.getDictDatas(reqVO);
        List<DictDataExcelVO> data = DictDataConvert.INSTANCE.convertList02(list);
        // 输出
        ExcelUtils.write(response, "字典数据.xls", "数据列表", DictDataExcelVO.class, data);
    }

}
